package com.n.passwordbook.LaunchWindow;

import com.n.passwordbook.MainWindow.MainWindow;
import com.n.passwordbook.PasswordBook.PasswordBook;
import com.n.passwordbook.Utils.CryptographyHelper;
import com.n.passwordbook.Utils.PageHelper;
import com.n.passwordbook.Utils.Settings;
import com.n.passwordbook.Utils.WindowHelper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.PasswordField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Text;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class LoginPage implements Initializable
{
    @FXML
    public Text txt_passwordWrong;
    @FXML
    public PasswordField pb_password;
    @FXML
    public Text txt_userName;


    public void hlOnActionGoToFirstLaunch(ActionEvent e)
    {
        PageHelper.changePageAndFadeOut(new FXMLLoader(getClass().getResource("FirstLaunch.fxml")));
    }

    public void hlOnActionOK(ActionEvent e)
    {
        if (!pb_password.getText().equals(""))
        {
            if (PasswordBook.checkIfPasswordBookPathValid(new File(Settings.getPasswordPath()), pb_password.getText()))
            {
                CryptographyHelper.setPBKey(pb_password.getText());
                PasswordBook.setPasswordBook(pb_password.getText(), Settings.getPasswordPath());
                pb_password.setText("");
                try
                {
                    TmpDataHelper.MainWindowPreloadThread.join();
                    WindowHelper.changeMainSceneRootWithFadeOutAndFadeIn(TmpDataHelper.MainWindowLoader,
                            MainWindow::initializeControllerManually,TmpDataHelper.MainWindowRoot);
                }
                catch (IOException | InterruptedException ioException)
                {
                    ioException.printStackTrace();
                }
            }
            else
            {
                txt_passwordWrong.setOpacity(1);
            }
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)
    {
        txt_passwordWrong.setOpacity(0);
        txt_userName.setText(PasswordBook.UserName);
        pb_password.requestFocus();
    }

    public void pbOnKeyPressedToOK(KeyEvent e)
    {
        if (e.getCode() == KeyCode.ENTER)
        {
            hlOnActionOK(new ActionEvent());
        }
    }
}
